//
//  TokenManager.swift
//  osc
//
//  Created by admin on 14/11/3.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import Foundation
import UIKit
import CoreData

class TokenManager {

    class func addToken(tokenM: TokenM){
        var entityName = NSStringFromClass(Tokencc.classForCoder())
        
        var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var managedObjectContext = appDelegate.managedObjectContext!
        
        var token = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext ) as  Tokencc
        
        
        token.access_token = tokenM.access_token!
        token.refresh_token = tokenM.refresh_token!
        token.token_type = tokenM.token_type!
        token.expires_in = tokenM.expires_in!
        token.uid = tokenM.uid!
        token.is_online = 0
        token.date_created = NSDate()
        
        //token.is_online = tokenM.is_online
        
        var savingError: NSError?
        
        if managedObjectContext.save(&savingError){
            println("Successfully saved the new Token")
            app.token = token
        } else {
            if let error = savingError{
                println("Failed to save the new Token. Error = \(error)")
            }
        }
        listToken()
    }
    
    //默认已排好序
    class func listToken()-> Tokencc?{
        
        var entityName = NSStringFromClass(Tokencc.classForCoder())
        var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var managedObjectContext = appDelegate.managedObjectContext!
        var fetchRequest : NSFetchRequest = NSFetchRequest(entityName: entityName)
        var error: NSError?

        var tokens = managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as [Tokencc]
        var token: Tokencc?
        
        /* Make sure we get the array */
        if tokens.count > 0{
            var counter = 1
            for token in tokens{
//                println("token \(counter) token.access_token = \(token.access_token)")
//                println("token \(counter) refresh_token = \(token.refresh_token)")
//                println("token \(counter) token.token_type = \(token.token_type)")
//                println("token \(counter) token.expires_in = \(token.expires_in)")
//                println("token \(counter) token.uid = \(token.uid)")
//                println("token \(counter) token.is_online = \(token.is_online)")
//                println("token \(counter) token.date_created = \(token.date_created)")
                counter++
            }
            token = tokens[0]
            
        } else {
            println("Could not find any token entities in the context")
            
        }
        return token
    }
    
    //登录有效返回true，未登录或登录无效返回false
    class func checkToken(token :Tokencc)->Bool{
        
        
//        println(" token.expires_in = \(token.expires_in)")
//        
//        println(" token.is_online = \(token.is_online)")
//        println(" token.date_created = \(token.date_created)")
        
        
        var now = NSDate()
        var created = token.date_created
        var timePassed = now.timeIntervalSinceDate(created)
        println("now=\(now.description)")
        println("created=\(token.date_created.description)")
        
        println("timePassed=\(timePassed)")
        
        var flag = token.expires_in.doubleValue - timePassed
        println("剩余=\(flag)秒")
        
        
        if flag > 0 {
            return true
        }else {
            return false
        }
        
    }
}